//
//  HJConversationManager.m
//  KaiChat
//
//  Created by lx on 2023/10/20.
//

#import "HJConversationManager.h"
#import "HJWebSocketManager.h"
#import "HJChatSessionModel.h"
#import "HJChatMessageModel.h"
#import "HJChatUserModel.h"
#import "HJChatGroupModel.h"
#import "HJIM.h"

@interface HJConversationManager()

@property (nonatomic, assign) NSInteger allMessageUnReadCount;


@end

@implementation HJConversationManager


- (void)addConversation:(HJChatSessionModel *)sessionModel completion:(void (^ _Nullable)(NSError * _Nonnull))completion {
    
    [self getConversationBySessionId:sessionModel.sessionId completion:^(HJChatSessionModel * _Nonnull obj) {
        sessionModel.unReadCount = toString(@(sessionModel.unReadCount.integerValue + obj.unReadCount.integerValue));
        [sessionModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            if (completion) {
                completion(isSuccess ? nil : [NSError errorWithCode:-10010]);
            }
        }];
    }];
    
}

- (void)addConversation:(HJChatSessionModel *)sessionModel addNot:(BOOL)addNot {
    HJChatSessionModel *obj = [self getConversationBySessionId:sessionModel.sessionId];

    if (sessionModel.isMute.boolValue) {
        sessionModel.unReadCount = @"0";
        if (sessionModel.muteMessageUnReadCount.intValue < 0) {
            sessionModel.muteMessageUnReadCount = @"0";
        } else {
            sessionModel.muteMessageUnReadCount = toString(@(sessionModel.muteMessageUnReadCount.integerValue + obj.muteMessageUnReadCount.integerValue));
        }
    } else {
        if (sessionModel.unReadCount.intValue < 0) {
            sessionModel.unReadCount = @"0";
        } else {
            sessionModel.unReadCount = toString(@(sessionModel.unReadCount.integerValue + obj.unReadCount.integerValue));
        }
    }
    
    BOOL res = [sessionModel bg_saveOrUpdate];
    NSLog(@"addConversation = %d", res);
    if (addNot) {
        [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationNotification object:sessionModel];
    }
}

- (void)addConversation:(HJChatSessionModel *)sessionModel {
    [self addConversation:sessionModel addNot:YES];
}

- (void)deleteConversationWithSessionId:(NSString *)sessionId completion:(void (^ _Nullable)(NSError * _Nonnull))completion {
    NSString *sql = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"sessionId"), bg_sqlValue(sessionId)];
    [HJChatSessionModel bg_deleteAsync:[HJChatSessionModel bg_tableName] where:sql complete:^(BOOL isSuccess) {
        [HJChatMessageModel bg_drop:[HJChatMessageModel bg_tableNameWithSessionId:sessionId]];
        dispatch_async_main_queue(^{
            if (completion) {
                completion(isSuccess ? nil : [NSError errorWithCode:-10010]);
            }
        });
    }];
}


- (void)allConversationListCompletion:(void (^__nullable)(NSArray *list))completion {
    NSString * where = [NSString stringWithFormat:@"where %@ is not null ORDER BY %@ desc",bg_sqlKey(@"sessionId"),bg_sqlKey(@"timestamp")];
    [HJChatSessionModel bg_findAsync:[HJChatSessionModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
        
        NSInteger totalCount = 0;
        for (HJChatSessionModel *sessionModel in array) {
                        
            if (sessionModel.chatType == HJChatTypeSingle) {//如果不是自己就查询
                
                totalCount += sessionModel.unReadCount.integerValue;
                
                NSString *userId = TJIM_isSelf(sessionModel.senderId) ? sessionModel.receiveId : sessionModel.senderId;
                HJChatFriendModel *chatUserModel = [HJIM.shareIM.userManager queryFriendInfoByFriendId:userId];
                if (chatUserModel) {
                    sessionModel.sessionName = chatUserModel.showName;
                    sessionModel.sessionAvatar = chatUserModel.avatar;
//                    sessionModel.disturb = toString(chatUserModel.disturb);
                }
  
            } else if (sessionModel.chatType == HJChatTypeGroup) {
                
                totalCount += sessionModel.unReadCount.integerValue;
   
                HJChatUserModel *chatUserModel = [HJIM.shareIM.userManager queryUserInfoByUserId:sessionModel.senderId];
                if (chatUserModel) {
                    sessionModel.senderName = chatUserModel.showName;
                }
                
                HJChatGroupModel *groupModel = [HJIM.shareIM.groupManager queryGroupInfoByGroupId:sessionModel.groupId];
                if (groupModel) {
                    sessionModel.sessionName = groupModel.name;
                    sessionModel.isMute = toString(groupModel.isMute);
                }
            }
        }
        
        dispatch_async_main_queue(^{
            [[NSNotificationCenter defaultCenter] postNotificationName:messageBadgeChangeNotification object:@(totalCount)];
        });
        
        if (completion) {
            completion(array);
        }
    }];
    
}

- (void)getConversationBySessionId:(NSString *)sessionId completion:(void (^__nullable)(HJChatSessionModel *sessionModel))completion {
    
    NSString *sql = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"sessionId"), bg_sqlValue(sessionId)];
    [HJChatSessionModel bg_findAsync:[HJChatSessionModel bg_tableName] where:sql complete:^(NSArray * _Nullable array) {
        
        HJChatSessionModel *sessionModel = array.lastObject;
        
        if (sessionModel) {
            NSString *tableName = [HJChatMessageModel bg_tableNameWithSessionId:sessionId];
            HJChatMessageModel *lastMessageModel = [HJChatMessageModel bg_find:tableName limit:1 orderBy:@"timestamp" desc:YES].lastObject;
            if (!lastMessageModel) {
                sessionModel.content = @"";
                sessionModel.senderId = @"";
                sessionModel.messageType = -1;
                [sessionModel bg_saveOrUpdate];
            } else {
                sessionModel.content = lastMessageModel.content;
                sessionModel.messageType = lastMessageModel.messageType;
                sessionModel.timestamp = lastMessageModel.timestamp;
                sessionModel.senderId = lastMessageModel.senderId;
            }
            completion(sessionModel);
        } else {
            completion(nil);
        }
    }];
}

- (HJChatSessionModel *)getConversationBySessionId:(NSString *)sessionId {
    NSString *sql = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"sessionId"), bg_sqlValue(sessionId)];
    NSString *tableName = [HJChatMessageModel bg_tableNameWithSessionId:sessionId];
    HJChatSessionModel *sessionModel = [HJChatSessionModel bg_find:[HJChatSessionModel bg_tableName] where:sql].lastObject;
    if (sessionModel) {
        HJChatMessageModel *lastMessageModel = [HJChatMessageModel bg_find:tableName limit:1 orderBy:@"timestamp" desc:YES].lastObject;
        if (!lastMessageModel) {
            sessionModel.content = @"";
            sessionModel.senderId = @"";
            sessionModel.messageType = -1;
            [sessionModel bg_saveOrUpdate];
        } else {
            sessionModel.content = lastMessageModel.content;
            sessionModel.messageType = lastMessageModel.messageType;
            sessionModel.timestamp = lastMessageModel.timestamp;
            sessionModel.senderId = lastMessageModel.senderId;
        }
    }
    return sessionModel;
}

- (void)updateBadge {
    //    NSString * where = [NSString stringWithFormat:@"where %@ is not null",bg_sqlKey(@"sessionId")];
    [HJChatSessionModel bg_findAllAsync:[HJChatSessionModel bg_tableName] complete:^(NSArray * _Nullable array) {
        NSInteger totalCount = 0;
        for (HJChatSessionModel *sessionModel in array) {
            if (sessionModel.chatType == HJChatTypeSingle || sessionModel.chatType == HJChatTypeGroup) {//如果不是自己就查询
                totalCount += sessionModel.unReadCount.integerValue;
            }
        }
        dispatch_async_main_queue(^{
            [[NSNotificationCenter defaultCenter] postNotificationName:messageBadgeChangeNotification object:@(totalCount)];
        });
    }];
}


- (void)getConversationInfo:(NSString *)sessionId chatType:(NSInteger)chatType complete:(void (^)(HJChatSessionModel * _Nullable model))complete {
    
}


- (void)getUnreadConversationMessageIds:(NSString *)sessionId completion:(void (^__nullable)(NSArray *list))completion {
    
    
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"sessionId"), bg_sqlValue(sessionId)];
    [HJChatSessionModel bg_findAsync:[HJChatSessionModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
    
        HJChatSessionModel *sessionModel = array.firstObject;
        if (sessionModel.unReadCount.intValue == 0) {
            if (completion) {
                completion(nil);
            }
            return;
        };
        
        NSArray *messageModels = [HJChatMessageModel bg_find:[HJChatMessageModel bg_tableNameWithSessionId:sessionId] limit:sessionModel.unReadCount.intValue orderBy:@"timestamp" desc:YES];
        
        NSMutableArray *msgIds = [NSMutableArray array];
        for (HJChatMessageModel *model in messageModels) {
            if (model.serverMsgId) {
                [msgIds addObject:model.serverMsgId];
            }
        }
        if (completion) {
            completion(msgIds);
        }
    }];
}

- (void)topWithSessionId:(NSString *)sessionId isTop:(BOOL)isTop isGroup:(BOOL)isGroup complete:(void (^__nullable)(NSError *error))complete {
    [HJNetworking.shareNetwork POSTBodyJSON:API_sessionTop parameters:@{
        @"session_id": sessionId,
        @"is_top": isTop ? @1 : @0,
        @"session_type": isGroup ? @2 : @1
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !complete ?: complete(nil);
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(error);
    }];
}


@end
